package com.nstar.base.util
{
	import mx.collections.ArrayCollection;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class RequestXMLUtils
	{
		//public function requestXmlToArrayCollection(url:String, label:String, data:String):ArrayCollection {
			
		//}
		
		public function RequestXMLUtils() {
			
		}
		
		public var loader:URLLoader;
		
		public function get data() {
			return loader.data;
		}
		
		public function requestUrl(url:String, method:Function) {
			var source:XML = new XML();
			var XMLURL:URLRequest = new URLRequest(url);
			loader = new URLLoader(XMLURL);
			loader.addEventListener("complete", method);
		}
		
		/**
		 * 将XML转为ArrayCollection
		 **/
		public function XmlToArrayCollection(source:XML, label:String, data:String):ArrayCollection {
			var array:ArrayCollection = new ArrayCollection();
			for each ( var element:XML in source.elements() ) {
				array.addItem({data:element[data],label:element[label]});
			}
			
			return array;
		}
		
		/**
		 * 将XML转为Tree可使用的XMLList
		 **/
		public function xmlToXmlListTree(source:XMLList, label:String, data:String):XMLList {
			var tree:XML =<root/>;
			for each ( var element:XML in source ) {
				tree.appendChild(nodeToAttribute(element,label,data));
			}
			
			return tree.child("node");
		}

		/**
		 * 将子节点转为属性
		 **/
		public function nodeToAttribute(source:XML, label:String, data:String):XML {
			
			var dest:XML = <node/>
			
			if(source == "") 
				return dest;
			
			if(source != null && source.@label != null) {
				dest.@label = source.child(label).toString();
				dest.@data = source.child(data).toString();
				var temp = xmlToXmlListTree(source.node,label,data);
				if(temp != null && temp != "" && temp != <node/>) {
					dest.node = temp;
				}
			}
			
			
			return dest;
		}
		
		/**
		 * 将多层的XML合并为一层
		 **/
		public function planeXML(source:XML):XML {
			var dest:XML = <node/>;
			for each(var element:XML in source) {
				getChildren(element,dest);
			}
			
			return dest;
		}
		
		private function getChildren(source:XML, destination:XML) {
			if(source.elements().length() == 0)
				destination.appendChild(source);
			else {
				for each(var element:XML in source.elements()) {
					getChildren(element,destination);
				}	
			}
				
		}
		
	}
}